
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ConnectMySQL {

    public static void main(String[] args) {
        // JDBC的一些配置
        String URL = "jdbc:mysql://localhost:3306/test";
        String driverName = "com.mysql.jdbc.Driver";
        String sql = "select * from students";
        String userName = "root";// root
        String password = "123456";// 123456
        Connection conn = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            Class.forName(driverName);// jdbc4.0 后无需使用这句进行驱动注册操作
            conn = DriverManager.getConnection(URL, userName, password);
            statement = conn.createStatement();
            resultSet = statement.executeQuery(sql);
            // id | stuno | name | gender | birthdate | major
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String stuno = resultSet.getString("stuno");
                Date date = resultSet.getDate("birthdate");
                System.out.print("id=" + id + " stuno=" + stuno + " birthdate=" + date);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {/*下面资源释放，可以使用try..with..resources语法简化*/
            if (resultSet != null) {
                try {
                    resultSet.close();
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                    statement = null;
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
            if (conn != null)
                try {
                    conn.close();
                    conn = null;
                } catch (SQLException e) {
                    e.printStackTrace();
                } 

        }
    }
}
